//
//  EngController_gstasks.m
//  Estate
//
//  Created by heyong on 16/9/6.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "EngController_gstasks.h"
#import "NewInspectionTextCell.h"
#import "LeaderAddInspController.h"

@interface EngController_gstasks ()
//添加按钮
@property (strong, nonatomic)UIButton *addBtn;
@end

@implementation EngController_gstasks
- (NSMutableArray *)dataArray{
    if(_dataArray==nil){
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView{
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, (DEF_SCREEN_HEIGHT-84-35*BIZ))];
        _tableView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];

        [LSUtility setExtraCellLineHidde:_tableView tabHeader:NO tabFooter:NO];
        [_tableView registerNib:[UINib nibWithNibName:@"NewInspectionTextCell" bundle:nil] forCellReuseIdentifier:@"detail"];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview: self.tableView];
    self.addBtn=[[UIButton alloc]initWithFrame:CGRECTS(260, 360, 100, 100)];
    [_addBtn setImage:[UIImage imageNamed:@"add_2"] forState:UIControlStateNormal];
    [self.view addSubview:_addBtn];
    [self.addBtn addTarget:self action:@selector(addContent) forControlEvents:UIControlEventTouchUpInside];
    [self initDataSource2];
       NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(initDataSource2) name:@"Refresh_xjzz" object:nil];
    
}

-(void)initDataSource2{

    
    [self.dataArray removeAllObjects];
    
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    //用户巡检项为1的数据
    NSString *sql_0=[NSString stringWithFormat:@"select id from INSPECT_USER_ITEM where inspect_process_id='%@' and inspect_current_state='1'",self.processId];
    FMResultSet *result_0=[db executeQuery:sql_0];
    
    //带巡检的id
    NSMutableArray *inspectArray=[NSMutableArray array];
    while ([result_0 next]) {
        
        NSString *userItemId=[result_0 stringForColumn:@"id"];
        
        //先查询巡检条数 如果大于2那就巡检过  解决检查过 却没有更改在状态的bug

        NSString *sql_check=[NSString stringWithFormat:@"select id FROM INSPECT_PROCESS_RECORD where inspect_user_item_id='%@'",userItemId];
        
        NSMutableArray *checkArray=[NSMutableArray array];
        
        FMResultSet *result_check=[db executeQuery:sql_check];
        
        while ([result_check next]) {
            NSString *checkid=[result_check stringForColumn:@"ID"];
            [checkArray addObject:checkid];
        }
        if(checkArray.count==1){
            [inspectArray addObject:userItemId];
        }
        
    }
    //作为条件
    NSString *inspectStr=[LSUtility dictionaryToJson_2:inspectArray];
    //转化为sql条件
    NSString *inspectCon=[LSUtility SymbolConversion:inspectStr];

    NSString *sqlStr=[NSString stringWithFormat:@"select count(*) as count,CASE WHEN sontab.pname IS NULL THEN (SELECT INSPECT_NAME FROM inspect_item where id=ipr.INSPECT_ITEM_ID) ELSE sontab.pname  END as pname,ipr.* from INSPECT_PROCESS_RECORD as ipr,(select (select iison.inspect_name from INSPECT_ITEM as iison where iison.id=ii.parent_id limit 1) as pname,ID FROM INSPECT_ITEM as ii GROUP BY ii.ID) as sontab where sontab.id=ipr.inspect_item_id and ipr.inspect_user_item_id in %@ and ipr.INSPECT_PROCESS_ID='%@' and  ipr.INSPECT_ITEM_STATE ='1' GROUP BY CASE  WHEN sontab.pname IS NULL THEN (SELECT INSPECT_NAME FROM inspect_item where id=ipr.INSPECT_ITEM_ID) ELSE sontab.pname END",inspectCon,self.processId];
    
    
    FMResultSet *result_1=[db executeQuery:sqlStr];
    //查询到分类
    NSMutableDictionary *dic;
    while ([result_1 next]) {
        //得到父类标题
        NSString *parentName=[result_1 stringForColumn:@"pname"];
        
        //得到分类条数
        NSString *count=[result_1 stringForColumn:@"count"];
        
        //得到巡检项id
//        NSString *item_id=[result_1 stringForColumn:@"INSPECT_ITEM_ID"];
        //查询实体表
//        NSString *sqlRecord=[NSString stringWithFormat:@"select sontab.pname ,ipr.*  from INSPECT_PROCESS_RECORD as ipr,(select CASE WHEN (select iison.inspect_name from INSPECT_ITEM as iison where iison.id=ii.parent_id limit 1) IS NULL THEN(select iison.inspect_name from INSPECT_ITEM as iison where iison.id=ii.parent_id limit 1) ELSE (select iison.inspect_name from INSPECT_ITEM as iison where iison.id=ii.parent_id limit 1) END as pname,ID FROM INSPECT_ITEM as ii GROUP BY ii.ID) as sontab where sontab.id=ipr.inspect_item_id and ipr.inspect_item_id not in('') and ipr.inspect_user_item_id in %@ and ipr.INSPECT_PROCESS_ID='%@' and ipr.INSPECT_ITEM_STATE='1' and ( pname='%@' or pname ISNULL) ORDER BY(ipr.INSPECT_USER_ID)",inspectCon,self.processId,parentName];
        
        //通过父类标题查询到下面的itemId
        NSString *sqlRecord=[NSString stringWithFormat:@"select CASE WHEN sontab.pname IS NULL THEN (SELECT INSPECT_NAME FROM inspect_item where id=ipr.INSPECT_ITEM_ID) ELSE sontab.pname  END as pname,ipr.* from INSPECT_PROCESS_RECORD as ipr,(select (select iison.inspect_name from INSPECT_ITEM as iison where iison.id=ii.parent_id limit 1) as pname,ID FROM INSPECT_ITEM as ii GROUP BY ii.ID) as sontab where sontab.id=ipr.inspect_item_id and ipr.inspect_item_id not in('') and ipr.inspect_user_item_id in %@  and ipr.INSPECT_PROCESS_ID='%@' and ipr.INSPECT_ITEM_STATE='1'  and ( pname='%@' or pname ISNULL) ORDER BY(ipr.INSPECT_USER_ID)",inspectCon,self.processId,parentName];
        
        FMResultSet *result_2=[db executeQuery:sqlRecord];
        
        NSMutableArray *DetailArr=[NSMutableArray array];
        while ([result_2 next]) {
            //流程记录id
            NSString *processId=[result_2 stringForColumn:@"ID"];
            NSString *pname=[result_2 stringForColumn:@"pname"];
            
            //只添加自己类所属下的数据
            if([pname isEqualToString:parentName]){
                
                //itemID
                NSString *itemId=[result_2 stringForColumn:@"INSPECT_ITEM_ID"];
                //根据itemId 查询实体表
                NSString *sql_item= [NSString stringWithFormat:@"select * from INSPECT_ITEM where id='%@'",itemId];
                FMResultSet *result_3=[db executeQuery:sql_item];
                NSMutableDictionary *muDic;
                
                while ([result_3 next]) {
                    //根据巡检项id 得到流程ID
                    NSString *inuserId=[LSUtility getInspectUserName:processId];
                    NSString *name=[LSUtility getuserIdByUserName:inuserId][@"REAL_NAME"];
                    
                    NSDictionary *dics=[result_3 resultDictionary];
                    muDic=[NSMutableDictionary dictionaryWithDictionary:dics];
                    if(name){
                        [muDic setObject:name forKey:@"name"];
                        [muDic setObject:inuserId forKey:@"inspectUserId"];
                    }
                    [muDic setObject:processId forKey:@"ids"];
                }
                //查询当前任务状态
                NSString *type=[result_2 stringForColumn:@"INSPECT_ITEM_STATE"];
                if([type isEqualToString:@"1"]){
                    type=@"待巡检";
                }else if ([type isEqualToString:@"2"]){
                    type=@"待汇总";
                }else if ([type isEqualToString:@"3"]){
                    type=@"待整改";
                }else if ([type isEqualToString:@"4"]){
                    type=@"待审阅";
                }else if ([type isEqualToString:@"5"]){
                    type=@"已完成";
                }
                //设置状态
                [muDic setObject:type forKey:@"type"];
                [DetailArr addObject:muDic];
            }
           

        }
        //存在数据
        if (DetailArr.count>0) {
            //设置标题
            NSString *title=[NSString stringWithFormat:@"%@  (%@条)",parentName,count];
            dic=[[NSMutableDictionary alloc] initWithObjectsAndKeys:DetailArr,DIC_ARARRY,title,DIC_TITILESTRING,[NSNumber numberWithInt:0],DIC_EXPANDED,nil];
            [self.dataArray addObject:dic];
        }
    }
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 40*BIZ)];
    if (!(self.dataArray.count > 0)) {
        label.text = @"您已没有要巡检的任务了!";
        label.textAlignment=1;
        label.font = [UIFont systemFontOfSize:24*BIZ];
        label.textColor=UIColorFromRGB(0x787878);
        [self.view addSubview:label];
    }else{
        [label removeFromSuperview];
    }
    [self.tableView reloadData];
    [db close];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section=indexPath.section;
    long row=indexPath.row;
//    得到改组下信息
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *reDic=array[row];
    
    NewInspectionTextCell *cell=[NewInspectionTextCell cellWithTableView:tableView];
    cell.title.text=[NSString stringWithFormat:@"(%@)%@",reDic[@"name"],[reDic objectForKey:@"INSPECT_NAME"]];
    cell.state.text=reDic[@"type"];
    
    return  cell;
}

//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH,(CELL_HEIGHT-5)*BIZ)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    
    //设置分组标题
    [eButton setTitle:[[self.dataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:16.*BIZ];
    
    //设置button的图片和标题的相对位置
    
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    UIImage *image=eButton.imageView.image;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, image.size.width)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(0, eButton.titleLabel.bounds.size.width+20, 0, -eButton.titleLabel.bounds.size.width)];
    
    //添加btn
    [hView addSubview: eButton];
    return hView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 5;
    }else{
        return 0.1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *reDic=array[indexPath.row];
    return [self cellHeightWithObj:[NSString stringWithFormat:@"(%@)%@",reDic[@"name"],[reDic objectForKey:@"INSPECT_NAME"]]];;
}


- (CGFloat)cellHeightWithObj:(NSString *)string{
    CGFloat cellHeight = 60;
    CGFloat mWidth = [UIScreen mainScreen].bounds.size.width - 100;
    cellHeight = [string boundingRectWithSize:CGSizeMake(mWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17*BIZ]} context:nil].size.height;
    if(cellHeight<=60){
        return 60;
    }else{
        return cellHeight;
    }
}

//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46*BIZ;
}

#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //得到改组下信息
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *dics=array[indexPath.row];
    //跳转详情
    LeaderAddInspController *leaderVC=[[LeaderAddInspController alloc]init];
    //传递记录ID
    leaderVC.prosessId=dics[@"ids"];
    //巡检人id
    leaderVC.inspectUserId=dics[@"inspectUserId"];
    //任务id
    leaderVC.taskId=self.processId;
    //流程流转
    leaderVC.flag=@"modState";
    
    [self.navigationController pushViewController:leaderVC animated:YES];
}

#pragma mark-添加巡检

- (void)addContent{
    //判断是否一键汇总
    NSArray *totalArr= [LSUtility getTotalByProcessID:self.processId];
    //已经一键汇总
    if(totalArr.count==0){
        LeaderAddInspController *leaderVC=[[LeaderAddInspController alloc]init];
        leaderVC.taskId=self.processId;
        leaderVC.inspectUserId=USERID;
        leaderVC.isEdit=YES;
        leaderVC.flag=@"add";
        [self.navigationController pushViewController:leaderVC animated:YES];
    }else{
//        LeaderAddInspController *leaderVC=[[LeaderAddInspController alloc]init];
//        leaderVC.taskId=self.processId;
//        leaderVC.inspectUserId=USERID;
//        leaderVC.isEdit=YES;
//        leaderVC.flag=@"add";
//        [self.navigationController pushViewController:leaderVC animated:YES];
        MBProgressHUD *progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:progressHUD];
        progressHUD.detailsLabelText = @"你已经汇总过该任务,不可以继续新建巡检项！";
        progressHUD.mode = MBProgressHUDModeText;
//        //指定距离中心点的X轴和Y轴的偏移量，如果不指定则在屏幕中间显示
        progressHUD.yOffset = -150.0f*BIZ;
        progressHUD.xOffset = -180.0f*BIZ;
        [progressHUD showAnimated:YES whileExecutingBlock:^{
            sleep(1.2);
        } completionBlock:^{
            [progressHUD removeFromSuperview];
        }];
    }
}

#pragma mark -- 内部调用
//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section{
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
    }else
    {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
}

//返回指定节是否是展开的
-(int)isExpanded:(long)section{
    NSDictionary *dic=[self.dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

//按钮被点击时触发
-(void)expandButtonClicked:(id)sender{
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
